package cn.livingCloud.controller.content.front;

import cn.livingCloud.dto.ImageUploadDto;
import cn.livingCloud.service.ImageUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * Created by sujiantang on 2015/12/21.
 */
@Controller
@RequestMapping("/admin/goods")
public class GoodsImageUploadController {
    @Autowired
    @Qualifier("imageUploadFrontServiceImpl")
    private ImageUploadService uploadService;

    @RequestMapping
    public void loadImage(HttpServletResponse response, HttpServletRequest request, String name) {
        uploadService.loadImage(response, request, name);
    }

    @RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
    public String uploadImage(@ModelAttribute("uploadDto") @Valid ImageUploadDto imageFile, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "goods/image_upload";
        }
        ImageUploadDto uploadDto = uploadService.saveUploadImage(imageFile);
        model.addAttribute("uploadDto", uploadDto);
        return "goods/image_upload";
    }

    @RequestMapping(value = "/upload.htm")
    public String showImageUpload(ImageUploadDto uploadDto, Model model) {
        model.addAttribute("uploadDto", uploadDto);
        return "goods/image_upload";
    }
}
